<template>
  <div>
    <div v-if="curSongInfo" :class="['play-bar', {'active':curSongInfo }]">
      <!-- 播放进度条 -->
      <progress-line  class="audioProgress"  :progress-width="audioProgressWidth"  @setProgressLine="setAudioProgress" />
      <div class="wrapper">
        <div class="play-bar-inside" @click="tiggerPlayWin()">
          <div class="bar-l">
            <router-link :to="{ path: '/song', query: { id: curSongInfo.id } }">
              <el-image :src="curSongInfo.albumPic" class="bar-cover-img">
                <template #placeholder>
                  <div class="image-slot">
                    <i-bi-emoji-smile-fill />
                  </div>
                </template>
              </el-image>
            </router-link>
            <div class="bar-name">
              <div class="song_name" @click.stop="toSong(curSongInfo.id)">
              <span>
                <span>{{ curSongInfo.name }}</span> -
                 <span v-for="(author, index) in curSongInfo.singer"
                       :key="author.name"
                       class="song_author"
                       @click="toSinger(author.id)"
                       style="cursor: pointer;">
                  {{ index !== 0 ? ' / ' + author.name : author.name }}
                </span>
              </span>
              </div>
              <div class="iconbtns">
                <i-bi-box2-heart />
                <i-bi-chat-dots />
                <i-bi-cloud-arrow-down />
              </div>
            </div>
          </div>
          <div class="bar-m">
            <div class="bar-control">
              <i-bi-heart  />
              <i-bi-skip-start-circle-fill  @click.stop="audioHandler('prev')" />
              <i-bi-pause-circle-fill v-if="isPlayed" class="iconfont" @click.stop="audioHandler('play')" />
              <i-bi-play-circle-fill v-else class="iconfont" @click.stop="audioHandler('play')" />
              <i-bi-skip-end-circle-fill  @click.stop="audioHandler('next')" />
              <i-bi-repeat v-if="info.playMode===0" @click.stop="changePlayMode" />
              <i-bi-repeat-1 v-if="info.playMode===1" @click.stop="changePlayMode" />
              <i-bi-shuffle v-if="info.playMode===2" @click.stop="changePlayMode" />
            </div>
          </div>
          <div class="bar-oper">
            <div class="bar-time">
              <span>{{util.formatSongTime( info.currentTime) }}</span> /{{ util.formatSongTime(curSongInfo.duration) }}
            </div>
            <!--音量条-->
            <el-popover placement="top" :width="50" trigger="hover" popper-class="volume-popover">
              <template #reference>
                <i-bi-volume-mute v-if="mutedIcon" style="font-size: 22px;"  @click.stop="volumeHandler" />
                <i-bi-volume-down v-else  style="font-size: 22px;"  @click.stop="volumeHandler" />
              </template>
              <div class="volume-control">
                <div class="slider-container">
                  <el-slider v-model="info.volumeNum" class="volume-slider" vertical height="100px"
                            :min="0.0" :max="1.0" :step="0.1" @change="setvolumeProgress" />
                </div>
                <div class="volume-value">{{ Math.round(info.volumeNum * 100) }}%</div>
              </div>
            </el-popover>
            <el-popover placement="top" :width="550" trigger="hover">
              <template #reference>
                <div class="playlist" @click.stop>
                  <span v-if="isShowPlayListTips" class="tips">已添加到播放列表</span>
                  <i-bi-music-note-list />
                  <div class="playlist-num">
                    {{ 99 > playList.length ? playList.length : '99+' }}
                  </div>
                </div>
              </template>
              <div class="playlist-container">
                <song-list :songList="playList" @tiggerPlayWin="tiggerPlayWin" :isScroll="true" :height="400" :typeSize="'mini'" :isShowTips="false"></song-list>
              </div>
            </el-popover>
          </div>
        </div>
      </div>
    </div>
    <el-drawer v-model="showPlayWin" :with-header="false" direction="btt" size="100%" :z-index="4">
      <PlayMusic v-if="curSongInfo" @tiggerPlayWin="tiggerPlayWin" :s-id="curSongInfo.id" :current-time="info.currentTime"></PlayMusic>
    </el-drawer>
  </div>

</template>

<script setup>
import ProgressLine from '@/components/Bar/ProgressLine.vue'
import SongList from '@/components/Bar/SongList.vue'
import { computed, defineEmits, inject, onBeforeUnmount, reactive, ref } from "vue";
import { usePlayStore } from '@/store/PlayStore'
import { useRouter } from "vue-router";
import emitter from '@/store/emitter'
import util from '@/tools/util.ts'
import PlayMusic from "./PlayMusic.vue";

const router = useRouter()
const emit = defineEmits();
const store = usePlayStore()
const showPlayWin = ref(false)
const info = reactive({
  lockName: 'active',
  manual: true,
  currentTime: inject('currentTime'), // 音频当前时长
  isMuted: false, // 是否禁音
  playMode: 0, // 播放模式  0循环播放、1单曲循环、2随机播放
  volumeNum: 1, // 音量值(0~1)
  oldVolume: 0, // 取消禁音的时候，设置保留的上一次的音量值
  isPip: false,
  timer: null,
  tipsTimer: null
})

console.log('父组件传递过来的时间:', inject('currentTime').value)

onBeforeUnmount(() => {
  clearTimeout(info.tipsTimer)
})
// 获取播放列表
const playIndex = computed(() => store.playIndex)
const playList = computed(() => store.playList)
const isPlayed = computed(() => store.isPlayed)
// 添加歌曲到播放列表后，弹窗tips提示
const isShowPlayListTips = computed(() => {
  const val = store.isShowPlayListTips
  if (val) {
    clearTimeout(info.tipsTimer)
    info.tipsTimer = setTimeout(() => {
      store.isShowPlayListTips = false
    }, 3000)
  }
  return val
})
function tiggerPlayWin(c){
  showPlayWin.value = (c !== undefined) ? c : !showPlayWin.value;
}
// 获取当前播放歌曲信息
const curSongInfo = computed(() => playList.value[playIndex.value])
// 切换播放模式
const changePlayMode = () => {
  info['playMode'] = info['playMode'] >= 2 ? 0 : info['playMode'] + 1
  emit('playAudioMode', info['playMode'])
}
// 音频播放进度条
const audioProgressWidth = computed(() => {
  return ((info.currentTime / curSongInfo.value.duration) * 100 + '%' )
})

// 音量禁音及取消操作
const volumeHandler = () => {
  info['isMuted'] = info['isMuted'] ? 0 : 1
  info['isMuted'] && (info['oldVolume'] = info['volumeNum'])
  info['volumeNum'] = info['isMuted'] ? 0 : info['oldVolume']
  emit('setVolumeHandler', info['isMuted'])
}
// 点击拖拽音量条，设置当前音量
const setvolumeProgress = (params) => {
  info['volumeNum'] = params
  info['oldVolume'] = params
  info['isMuted'] = params ? 0 : 1
  emitter.emit('setvolumeProgress', params)
}

// 是否静音
const mutedIcon = computed(() => {
  return info['isMuted']
})
// 音频播放/暂停/上一首/下一首事件
const audioHandler = (type) => {
  emitter.emit('playAudioType', type)
  if (info['isPip']) {
    changePipSong()
  }
}
// 点击拖拽进度条，设置当前时间
const setAudioProgress = (params) => {
  info['initAudioReady'] = false
  info.currentTime = params.val * curSongInfo.value.duration
  // 拖拽的时候，不实时更改音频的时间
  console.log("点击进度条",params,"播放时间", info.currentTime)
  if (params.flag) {
    emitter.emit("setAudioProgress", info.currentTime)
  }
}
// 画中画
const canvas = document.createElement('canvas')
canvas.width = 250
canvas.height = 250
const video = document.createElement('video')
video.srcObject = canvas.captureStream()
video.muted = true
//跳转歌曲信息
const toSong = (id) => {
  router.push({ path: '/song', query: { id: id } });
}
// 切换画中画里音频相关信息
const changePipSong = () => {
  navigator.mediaSession.metadata = new MediaMetadata({
    title: curSongInfo.value.name,
    artist: curSongInfo.value.singer[0].name,
    album: curSongInfo.value.album.name,
    artwork: [{ src: curSongInfo.value.album.picUrl }]
  })
  if (info['isPip']) {
    showPictureInPictureWindow()
  } else {
    document.exitPictureInPicture()
  }
}
const showPictureInPictureWindow = async () => {
  const image = new Image()
  image.crossOrigin = true
  image.src = [...navigator.mediaSession.metadata.artwork].pop().src
  await image.decode()
  canvas.getContext('2d').drawImage(image, 0, 0, 250, 250)
  await video.play()
  await video.requestPictureInPicture()
}
const actionHandlers = [
  ['play', 'play'],
  ['pause', 'play'],
  ['previoustrack', 'prev'],
  ['nexttrack', 'next']
]
for (const [action, type] of actionHandlers) {
  navigator.mediaSession.setActionHandler(action, () => {
    audioHandler(type)
    changePipSong()
    if (action == 'play') {
      navigator.mediaSession.playbackState = 'playing'
    } else if (action == 'pause') {
      navigator.mediaSession.playbackState = 'paused'
    }
  })
}
// 退出画中画
video.addEventListener(
  'leavepictureinpicture',
  () => {
    info['isPip'] = false
  },
  false
)
</script>
<style scoped lang="scss">
.play-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 5;
  width: 100%;
  height: 70px;
  background: var(--el-bg-color-page);
  box-shadow: 0 5px 40px -1px rgba(2, 10, 18, 0.1);
  transition: all 0.4s ease-out;
  transform: translateY(100%);

  &.active {
    transform: translateY(0);
  }
}

.audioProgress {
  position: absolute;
  top: -6px;
  z-index: 9;
}

.wrapper {
  background: var(--transparent-1);
}

.play-bar-inside {
  display: flex;
  justify-content: space-between;
  height: 70px;
  align-items: center;
  margin-left: 20px;
  margin-right: 20px;

  .bar-l {
    display: flex;
    flex: 1;
    flex-direction: row;
  }
  .bar-m{
    flex: 1;
  }

  .bar-cover-img {
    width: 50px;
    height: 50px;
    border-radius: 4px;
    box-shadow: 0 0 15px 5px rgba(var(--color-text-height), 0.15);
  }

  .bar-name {
    font-size: 0;
    padding-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;

    .song_name {
      flex: 3;
      align-content: center;
      font-size: 14px;
      font-weight: bold;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
      color: var(--el-text-color-primary);
      >span{
        .song_author {
          margin-left: 10px;
          line-height: 12px;
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }

    }
    .iconbtns{
      flex: 2;
      svg {
        font-size: 15px;
        margin-left: 10px;
        margin-right: 10px;
        cursor: pointer;
        color: var(--transparent-4);
      }
    }

  }

  .icon-collect,
  .icon-collect-active {
    font-size: 24px;
    line-height: 24px;
    margin: 0 15px;
    cursor: pointer;
  }

  .bar-time {
    width: 115px;
    line-height: 50px;
    font-size: 14px;
    color: #606266;
    text-align: center;
  }

  .bar-control {
    display: flex;
    padding: 10px 0;
    line-height: 1;
    align-items: center;
    justify-content: center;
    color: var(--el-text-color-regular);
    svg {
      margin: 0 20px;
      font-size: 20px;
      cursor: pointer;
    }
    .iconfont{
      color: var(--my-bg-menu-active);
      font-size: 30px;
    }
  }

  .volumeLine {
    width: 150px;
    margin: 0 10px;
  }

  .bar-oper {
    position: relative;
    display: flex;
    flex: 1;
    font-size: 0;
    line-height: 50px;
    padding-left: 30px;
    align-items: center;
    justify-content: flex-end;
    color: var(--transparent-4);
  }

  .playlist {
    position: relative;
    display: flex;
    align-items: center;
    margin-left: 15px;
    line-height: 70px;
    height: 70px;
    cursor: pointer;

    svg {
      font-size: 15px;
    }

    .playlist-num {
      position: absolute;
      top: 25%;
      left: 90%;
      font-size: 12px;
      line-height: 12px;
    }

    .tips {
      position: absolute;
      top: -50px;
      left: -60px;
      background: rgba(0, 0, 0, 0.8);
      display: inline-block;
      width: 120px;
      font-size: 12px;
      text-align: center;
      height: 30px;
      line-height: 30px;
      padding: 5px 0;
      border-radius: 4px;

      &::after {
        content: '';
        position: absolute;
        bottom: -6px;
        left: 47%;
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 6px 8px 0 8px;
        border-color: rgba(0, 0, 0, 0.8) transparent transparent transparent;
      }
    }
  }

  .volume-main {
    flex: 1;
    padding: 10px 0;
    display: flex;
    align-items: center;
    position: relative;
  }

  .volume-control {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12px 4px;
    background: var(--el-bg-color);
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    
    .slider-container {
      margin-bottom: 8px;
      width: 20px;
      
      :deep(.el-slider) {
        .el-slider__runway {
          width: 4px;
          margin: 0 8px;
        }
        
        .el-slider__button {
          width: 10px;
          height: 10px;
        }
      }
    }
    
    .volume-value {
      font-size: 12px;
      line-height: 1;
      color: var(--el-text-color-regular);
      text-align: center;
      width: 100%;
      padding: 0 2px;
    }
  }
}

:deep(.volume-popover.el-popper) {
  padding: 0;
  border: none;
  background: transparent;
  box-shadow: none;
  width: 50px!important;
  
  .el-popper__arrow {
    display: none;
  }
}
</style>
